#include "MiBand4/MiBand4.h"
BaiduThings baidu;

static char dec2hex(short int c)
{
    if (0 <= c && c <= 9)
    {
        return c + '0';
    }
    else if (10 <= c && c <= 15)
    {
        return c + 'A' - 10;
    }
    else
    {
        return -1;
    }
}

static String urlencode(String str)
{
    String urlcode = "";
    int i = 0;
    int len = str.length();
    for (i = 0; i < len; ++i)
    {
        char c = str[i];
        if (('0' <= c && c <= '9') ||
            ('a' <= c && c <= 'z') ||
            ('A' <= c && c <= 'Z') ||
            c == '/' || c == '.')
        {
            urlcode += String(c);
        }
        else
        {
            int j = (short int)c;
            if (j < 0)
                j += 256;
            int i1, i0;
            i1 = j / 16;
            i0 = j - i1 * 16;
            urlcode += String('%');
            urlcode += String((char)dec2hex(i1));
            urlcode += String((char)dec2hex(i0));
        }
    }
    return urlcode;
}

bool BaiduThings::getToken()
{
    http.begin(url_baidu_token);
    int r = http.GET();
    if (r == HTTP_CODE_OK)
    {
        String s = http.getString();
        DynamicJsonDocument doc(2048);
        deserializeJson(doc, s);
        if (doc.containsKey("access_token"))
        {
            token = doc["access_token"].as<String>();
            Serial.println(token);
            http.end();
            return true;
        }
    }
    http.end();
    return false;
}

String BaiduThings::getAsr(uint8_t *pcm, size_t size)
{
    http.begin(url_baidu_asr + token);
    http.addHeader("Content-Type", "audio/pcm;rate=16000");
    int r = http.POST(pcm, size);
    if (r == HTTP_CODE_OK)
    {
        String s = http.getString();
        DynamicJsonDocument doc(1024);
        deserializeJson(doc, s);
        String res = doc["result"][0];
        http.end();
        doc.clear();
        doc.garbageCollect();
        return res;
    }
    http.end();
    return "";
}

bool BaiduThings::getBot(String s)
{
    String post_data = "{\"version\":\"3.0\",\"service_id\":\"" BAIDU_BOT_ID "\",\"session_id\":\"" + bot_session_id + "\",\"log_id\":\"265325663256\",\"request\":{\"terminal_id\":\"896589655\",\"query\":\"" + s + "\",\"query_info\":{\"source\":\"ASR\"},\"hyper_params\":{\"chat_style\":\"lively\"}}}";
    HTTPClient _http;
    _http.begin(url_baidu_bot + token);
    _http.addHeader("Content-Type", "application/json; charset=UTF-8");
    int code = _http.POST(post_data);
    if (code != HTTP_CODE_OK)
    {
        Serial.println(code);
        _http.end();
        return false;
    }
    String res = _http.getString();
    _http.end();
    doc.clear();
    doc.garbageCollect();
    DeserializationError error = deserializeJson(doc, res, DeserializationOption::NestingLimit(12));
    if (error)
    {
        Serial.print("deserializeJson() failed: ");
        Serial.println(error.c_str());
        return false;
    }
    bot_session_id = doc["result"]["session_id"].as<String>();
    obj = doc["result"]["responses"][0];
    return true;
}